import { CONFIG } from '@/constants/config';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { api } from '@/services/api';
import { useModel } from '@umijs/max';
import { Button, Card, Form, Input, message } from 'antd';
import React, { useRef } from 'react';
import styles from './index.less';
import type { TokenResponse } from '@/services/generated/models';

interface LoginFormValues {
  username: string;
  password: string;
}

const LoginPage: React.FC = () => {
  const [loading, setLoading] = React.useState(false);
  const { refresh } = useModel('@@initialState');
  const formRef = useRef(null);

  const handleSubmit = async (values: LoginFormValues) => {
    try {
      setLoading(true);
      // 1. 获取 token
      const response = await api.token.tokenCreate({
        tokenObtainRequestRequest: values,
      });

      console.log('[Login] Token response:', response);

      // 2. 存储 token 和设备 ID
      localStorage.setItem(CONFIG.CACHE.TOKEN_KEY, response.access);
      localStorage.setItem(CONFIG.CACHE.REFRESH_TOKEN_KEY, response.refresh);
      localStorage.setItem(CONFIG.CACHE.DEVICE_ID_KEY, response.deviceId);
      
      // 3. 获取用户信息
      const userInfo = await api.accounts.accountsUsersMeRetrieve();
      localStorage.setItem(
        CONFIG.CACHE.USER_INFO_KEY,
        JSON.stringify(userInfo),
      );

      // 4. 刷新用户状态
      await refresh();

      message.success('登录成功');

      // 5. 跳转到首页
      window.location.href = '/';
    } catch (error) {
      // 清除所有认证信息
      localStorage.removeItem(CONFIG.CACHE.TOKEN_KEY);
      localStorage.removeItem(CONFIG.CACHE.REFRESH_TOKEN_KEY);
      localStorage.removeItem(CONFIG.CACHE.DEVICE_ID_KEY);
      localStorage.removeItem(CONFIG.CACHE.USER_INFO_KEY);
      // 错误消息已在 api.ts 中处理
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <Card title={CONFIG.SYSTEM.NAME} style={{ width: 400 }}>
        <Form<LoginFormValues>
          ref={formRef}
          name="login"
          onFinish={handleSubmit}
          initialValues={{ username: '', password: '' }}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              size="large"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default LoginPage;
